﻿using System.Collections.Generic;
using System.IO;

namespace TdxApiPool.Invoker
{
    public class DllManager
    {
        public static readonly string DllPath = @".\TdxHqApi.dll";
        
        public static readonly DllManager Instance = new DllManager();

        public Dictionary<string,DllInvoker> Invokers { get; }

        private DllManager()
        {
            Invokers = Generate();
        }
        
        private Dictionary<string,DllInvoker> Generate()
        {
            var dllInvokers = new Dictionary<string, DllInvoker>();
            var baseMarketHost = Config.GetConfig().BaseMarket.Host;
            foreach (var host in baseMarketHost)
            {
                for (int i = 0; i < host.ConnectCount; i++)
                {
                    var destFilePath = @".\" + host.IpAddress + "_" + i + ".dll";
                    if(!File.Exists(destFilePath))
                    {
                        File.Copy(DllPath, destFilePath);
                    }
                    dllInvokers.Add(host.IpAddress + "_" + i, new DllInvoker(destFilePath));
                }
            }

            var fasterMarketHost = Config.GetConfig().FasterMarket.Host;
            foreach (var host in fasterMarketHost)
            {
                for (int i = 0; i < host.ConnectCount; i++)
                {
                    var destFilePath = @".\" + host.IpAddress + "_faster_" + i + ".dll";
                    if (!File.Exists(destFilePath))
                    {
                        File.Copy(DllPath, destFilePath);
                    }
                    dllInvokers.Add(host.IpAddress + "_faster_" + i, new DllInvoker(destFilePath));
                }
            }

            var queryHost = Config.GetConfig().Query.Host;
            for (var i = 0; i < queryHost.ConnectCount; i++)
            {
                var destFilePath = @".\" + queryHost.IpAddress + "_query_" + i + ".dll";
                if(!File.Exists(destFilePath))
                {
                    File.Copy(DllPath, destFilePath);
                }
                dllInvokers.Add(queryHost.IpAddress + "_query_" + i, new DllInvoker(destFilePath));
            }
            
            return dllInvokers;
        }
    }
}